package com.yft.controller.purchasepos;

import com.yft.dao.base.BaseConstant;
import com.yft.dao.base.BaseUtils;
import com.yft.entity.base.Order;
import com.yft.entity.base.OrderSort;
import com.yft.entity.base.Pager;
import com.yft.entity.base.PagerImpl;
import com.yft.entity.login.SysMember;
import com.yft.entity.posinformation.PosModel;
import com.yft.entity.posinformation.PosSupplyChannel;
import com.yft.entity.purchasepos.PosPurchaseOrderDetail;
import com.yft.entity.purchasepos.PosPurchaseOrderHeader;
import com.yft.enumeration.PosPattern;
import com.yft.enumeration.PosPurchaseOrderStatus;
import com.yft.service.purchasepos.PosPurchaseOrderDetailService;
import com.yft.service.purchasepos.PosPurchaseOrderHeaderService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


@Controller
public class PosPurchaseOrderController {
	private static final String controllerPath = "/yft/posPurchaseOrder/";
	private String jsonViewpath = "/admin/pos_purchase_order/jsp/json/";
	
	@Autowired(required = true)
	private PosPurchaseOrderHeaderService posPurchaseOrderHeaderService;

    @Autowired(required = true)
    private PosPurchaseOrderDetailService posPurchaseOrderDetailService;

	private boolean checkNullBlank(Object[] array){
		if(array==null || array.length==0){
			return false;
		}
		for(int i=0;i<array.length;i++){
			if(array[i] != null && !"".equals(((String)array[i]).trim())){
				continue;
			}else{
				return false;
			}
		}
		return true;
	}

    /**
     * 获取采购单表头
     * @param request
     * @param response
     * @param modelMap
     * @return
     */
	@RequestMapping(controllerPath + "getPosPurchaseOrderHeaderList.html")
	public String getPosPurchaseOrderHeaderList(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap) {
		PosPurchaseOrderHeader condition = new PosPurchaseOrderHeader();
		Pager pager = new PagerImpl();
		String purchaseOrderNo = StringUtils.trimToEmpty(request.getParameter("purchaseOrderNo"));
		String limit = request.getParameter("limit");
		if(purchaseOrderNo!=null && purchaseOrderNo.length()>0){
            condition.setSe_purchaseOrderNo(purchaseOrderNo);
		}
		int pageSize = 7;
		if (limit != null && limit.length() > 0)
			pageSize = NumberUtils.toInt(limit) > 0 ? NumberUtils.toInt(limit) : pageSize;
		String start = request.getParameter("start");
		int page = 1;
		if (start != null && start.length() > 0)
			page = NumberUtils.toInt(start) / pageSize + 1;
		pager.setPageSize(pageSize);
		pager.setPage(page);
		Order order = new Order();
		order.addOrder("createTime", OrderSort.DESC);
		
		List<PosPurchaseOrderHeader> posPurchaseOrderHeaderList =  posPurchaseOrderHeaderService.getPosPurchaseOrderHeaderList(condition, order, pager);

        modelMap.addAttribute("totalProperty",pager.getRecordCount());
        modelMap.addAttribute("posPurchaseOrderHeaderList",posPurchaseOrderHeaderList);
		
		return jsonViewpath + "pos_purchase_order_header";
	}

    /**
     * 获取采购单表体
     * @param request
     * @param response
     * @param modelMap
     * @return
     */
    @RequestMapping(controllerPath + "getPosPurchaseOrderDetailList.html")
    public String getPosPurchaseOrderDetailList(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap) {
        PosPurchaseOrderDetail condition = new PosPurchaseOrderDetail();
        Pager pager = new PagerImpl();
        String purchaseOrderId = StringUtils.trimToEmpty(request.getParameter("purchaseOrderId"));
        String limit = request.getParameter("limit");
        if(purchaseOrderId!=null && purchaseOrderId.length()>0){
        }
        int pageSize = 7;
        if (limit != null && limit.length() > 0)
            pageSize = NumberUtils.toInt(limit) > 0 ? NumberUtils.toInt(limit) : pageSize;
        String start = request.getParameter("start");
        int page = 1;
        if (start != null && start.length() > 0)
            page = NumberUtils.toInt(start) / pageSize + 1;
        pager.setPageSize(pageSize);
        pager.setPage(page);
        Order order = new Order();
        order.addOrder("createTime", OrderSort.DESC);

        List<PosPurchaseOrderDetail> posPurchaseOrderDetailList =  posPurchaseOrderDetailService.getPosPurchaseOrderDetailList(condition, order, pager);

        modelMap.addAttribute("totalProperty",pager.getRecordCount());
        modelMap.addAttribute("posPurchaseOrderDetailList",posPurchaseOrderDetailList);

        return jsonViewpath + "pos_purchase_order_detail";
    }

    @RequestMapping(controllerPath + "clearSessionPurchaseOrderItem.html")
    public String clearSessionPurchaseOrderItem(HttpServletRequest request,HttpServletResponse response, ModelMap model) {
        request.getSession().setAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_ADD,null);
        model.addAttribute("success",true);
        return "message/messageJson";
    }

    /**
     * 获得session中的订单表体
     * @param request
     * @param response

     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(controllerPath+"getSessionPurchaseOrderItemList.html")
    public String getSessionPurchaseOrderItemList(HttpServletRequest request,HttpServletResponse response, ModelMap model) {
        String isAdd = request.getParameter("isAdd");
        if(BaseUtils.checkNullBlank(isAdd)){
            Object o;
            if("1".equals(isAdd.trim())){
                o = request.getSession().getAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_ADD);
            }else{
                o = request.getSession().getAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_UPDATE);
            }
            if(o == null){
                model.addAttribute("totalProperty",0);
            }else{
                List<PosPurchaseOrderDetail> posPurchaseOrderDetailList = new ArrayList<PosPurchaseOrderDetail>();
                posPurchaseOrderDetailList.addAll((List<PosPurchaseOrderDetail>)o);
                model.addAttribute("totalProperty",posPurchaseOrderDetailList.size());
                model.addAttribute("posPurchaseOrderDetailList",posPurchaseOrderDetailList);
            }
        }
        return jsonViewpath + "pos_purchase_order_detail";
    }

    /**
     * 构建QualityAdjustDetail进session
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(controllerPath+"addPurchaseOrderItemToSession.html")
    public String addPurchaseOrderItemToSession(HttpServletRequest request,HttpServletResponse response, ModelMap model) {

        String machineSnCode = StringUtils.trimToEmpty(request.getParameter("machineSnCode"));
        String terminalSn = StringUtils.trimToEmpty(request.getParameter("terminalSn"));
        String passwordKeySn = StringUtils.trimToEmpty(request.getParameter("passwordKeySn"));
        String posModelIdStr = StringUtils.trimToEmpty(request.getParameter("posModelId"));
        String pattern = StringUtils.trimToEmpty(request.getParameter("pattern"));
        String modelName = StringUtils.trimToEmpty(request.getParameter("modelName"));
        //String qualityStr = StringUtils.trimToEmpty(request.getParameter("quality"));
        String isAdd = StringUtils.trimToEmpty(request.getParameter("isAdd"));
       // Integer quality = NumberUtils.toInt(qualityStr, -1);
        Integer posModelId = NumberUtils.toInt(posModelIdStr,-1);
//        if(BaseUtils.checkNullBlank(new String[]{machineSnCode,terminalSn,passwordKeySn,posModelIdStr,isAdd,pattern,modelName,qualityStr}) &&  quality!=-1 &&  posModelId!=-1){
        if(BaseUtils.checkNullBlank(new String[]{machineSnCode,passwordKeySn,posModelIdStr,isAdd,pattern,modelName}) &&  posModelId!=-1){
            try {
                List<PosPurchaseOrderDetail> poilist;
                Object o;
                if("1".equals(isAdd.trim()))
                    o = request.getSession().getAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_ADD);
                else
                    o = request.getSession().getAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_UPDATE);

                if(o != null)
                    poilist = (List<PosPurchaseOrderDetail>)o;
                else
                    poilist = new ArrayList<PosPurchaseOrderDetail>();

                PosPurchaseOrderDetail poi = new PosPurchaseOrderDetail();
                poi.setMachineSnCode(machineSnCode);
                if(BaseUtils.checkNullBlank(terminalSn))
                    poi.setTerminalSn(terminalSn);
                poi.setPasswordKeySn(passwordKeySn);
                poi.setPosModelId(posModelId);
                poi.setPosModel(new PosModel(posModelId));
                poi.setPattern(PosPattern.valueOf(pattern));
                poi.setModelName(modelName);
                poi.setQuality(1);
                poi.setIndex(poilist.size());
                poilist.add(poi);

                if("1".equals(isAdd.trim()))
                    request.getSession().setAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_ADD, poilist);
                else
                    request.getSession().setAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_UPDATE, poilist);
                model.addAttribute("success",true);
            } catch (Exception e) {
                model.addAttribute("success",false);
            }
        }else{
            model.addAttribute("success",false);
        }
        return "message/messageJson";
    }

    /**
     * 删除session中产品
     * @param model
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(controllerPath + "deletePosItemInSessionForP.html")
    public String deletePosItemInSessionForP(ModelMap model, HttpServletRequest request,HttpServletResponse response){
        String indexsInSessionS = request.getParameter("indexsInSession");
        String idsForUpdateS = request.getParameter("idsForUpdate");

        if(indexsInSessionS != null && !indexsInSessionS.trim().equals("")){
            Object o = request.getSession().getAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_ADD);
            if(o == null){
                model.addAttribute("success",false);
                return "message/messageJson";
            }else{
                try {
                    String[] ss = indexsInSessionS.split(",");
                    List<PosPurchaseOrderDetail> poilist = (List<PosPurchaseOrderDetail>)o;
                    List<PosPurchaseOrderDetail> waitRemove = new ArrayList<PosPurchaseOrderDetail>();
                    for(String ts : ss){
                        for(int i = 0 ; i<poilist.size(); i++){
                            if(poilist.get(i).getIndex().intValue() == Integer.valueOf(ts).intValue()){
                                waitRemove.add(poilist.get(i));
                            }
                        }
                    }
                    poilist.removeAll(waitRemove);
                    for(int i = 0 ; i < poilist.size() ;i++){
                        poilist.get(i).setIndex(i);
                    }
                    request.getSession().setAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_ADD, poilist);
                } catch (Exception e) {
                    model.addAttribute("success",false);
                    return "message/messageJson";
                }
            }
        }else if(idsForUpdateS != null && !idsForUpdateS.trim().equals("")){
            Object o = request.getSession().getAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_UPDATE);
            if(o == null){
                model.addAttribute("success",false);
                return "message/messageJson";
            }else{
                try {
                    String[] ss = idsForUpdateS.split(",");
                    List<PosPurchaseOrderDetail> poilist = (List<PosPurchaseOrderDetail>)o;
                    List<PosPurchaseOrderDetail> waitRemove = new ArrayList<PosPurchaseOrderDetail>();
                    for(String ts : ss){
                        for(int i = 0 ; i<poilist.size(); i++){
                            if(poilist.get(i).getIndex().intValue() == Integer.valueOf(ts).intValue()){
                                waitRemove.add(poilist.get(i));
                            }
                        }
                    }
                    poilist.removeAll(waitRemove);
                    for(int i = 0 ; i < poilist.size() ;i++){
                        poilist.get(i).setIndex(i);
                    }
                    request.getSession().setAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_UPDATE, poilist);
                } catch (Exception e) {
                    model.addAttribute("success",false);
                    return "message/messageJson";
                }
            }
        }
        model.addAttribute("success",true);
        return "message/messageJson";
    }

        /**
     * 重置订单更新面板items
     * @param model
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(controllerPath + "resetSessionPurchaseOrderItem.html")
    public String resetSessionPurchaseOrderItem(ModelMap model, HttpServletRequest request,HttpServletResponse response){
        String purchaseOrderHeaderId = request.getParameter("purchaseOrderHeaderId");
        if(BaseUtils.checkNullBlank(purchaseOrderHeaderId)){
            PosPurchaseOrderDetail con = new PosPurchaseOrderDetail();
            con.setHeaderId(purchaseOrderHeaderId);
            List<PosPurchaseOrderDetail> detailList = posPurchaseOrderDetailService.getPosPurchaseOrderDetailList(con, null, null);
            for(int i = 0;i<detailList.size();i++){
                detailList.get(i).setIndex(i);
            }
            request.getSession().setAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_UPDATE, detailList);
            model.addAttribute("success",true);
        }else{
            model.addAttribute("success",false);
        }
        return "message/messageJson";
    }

        /**
     * 开启订单更新面板
     * @param model
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(controllerPath + "getPurchaseOrderForUpdate.html")
    public String getPurchaseOrderForUpdate(ModelMap model, HttpServletRequest request,HttpServletResponse response){
        String headerId = request.getParameter("headerId");
        if(BaseUtils.checkNullBlank(headerId)){
            PosPurchaseOrderHeader posPurchaseOrderHeader = posPurchaseOrderHeaderService.getPosPurchaseOrderHeader(headerId);
            if(posPurchaseOrderHeader == null  || (posPurchaseOrderHeader.getPosPurchaseOrderStatus() != null && !PosPurchaseOrderStatus.NEW.equals(posPurchaseOrderHeader.getPosPurchaseOrderStatus()))){
                model.addAttribute("error","数据不存在或者单据状态不是新增");
                model.addAttribute("success",false);
            }else{
                model.addAttribute("posPurchaseOrderHeader",posPurchaseOrderHeader);
                PosPurchaseOrderDetail con = new PosPurchaseOrderDetail();
                con.setHeaderId(headerId);
                List<PosPurchaseOrderDetail> detailList = posPurchaseOrderDetailService.getPosPurchaseOrderDetailList(con, null, null);
                for(int i = 0;i<detailList.size();i++){
                    detailList.get(i).setIndex(i);
                }
                request.getSession().setAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_UPDATE, detailList);
                model.addAttribute("success",true);
            }
        }else{
            model.addAttribute("error","参数错误");
            model.addAttribute("success",false);
        }
        return jsonViewpath + "pos_purchase_order_header_update";
    }

    /**
     * 采购单生成
     * @param model
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(controllerPath + "addPosPurchaseOrder.html")
    public String addPosPurchaseOrder(ModelMap model, HttpServletRequest request,HttpServletResponse response){
        String supplyChannelIdStr = StringUtils.trimToEmpty(request.getParameter("supplyChannelId"));
        String expressNo = StringUtils.trimToEmpty(request.getParameter("expressNo"));
        String supplyChannel = StringUtils.trimToEmpty(request.getParameter("supplyChannel"));
        Integer supplyChannelId = NumberUtils.toInt(supplyChannelIdStr, -1);
        if(BaseUtils.checkNullBlank(new String[]{supplyChannelIdStr,expressNo,supplyChannel}) &&  supplyChannelId!=-1){
            Object o = request.getSession().getAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_ADD);
            if(o == null){
                model.addAttribute("error", "seesion为空");
                model.addAttribute("success",false);
                return "message/messageJson";
            }
            List<PosPurchaseOrderDetail> itemList = (List<PosPurchaseOrderDetail>)o;
            if(itemList.isEmpty()){
                model.addAttribute("error", "session中明细为空");
                model.addAttribute("success",false);
                return "message/messageJson";
            }
            PosPurchaseOrderHeader purchaseOrderHeader = new PosPurchaseOrderHeader();
            purchaseOrderHeader.setExpressNo(expressNo);
            purchaseOrderHeader.setPosPurchaseOrderStatus(PosPurchaseOrderStatus.NEW);
            purchaseOrderHeader.setChannelName(supplyChannel);
            purchaseOrderHeader.setSupplyChannelId(supplyChannelId);
            purchaseOrderHeader.setPosSupplyChannel(new PosSupplyChannel(supplyChannelId));
            SysMember member =  (SysMember)request.getSession().getAttribute(BaseConstant.SESSION_MEMBER);
            boolean flag = posPurchaseOrderHeaderService.addPosPurchaseOrder(purchaseOrderHeader, itemList);
            model.addAttribute("success",flag);
        }else{
            model.addAttribute("error", "参数错误");
            model.addAttribute("success",false);
        }
        return "message/messageJson";
    }




    /**
     * 订单更新
     * @param model
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(controllerPath + "doUpdatePosPurchaseOrder.html")
    public String doUpdatePosPurchaseOrder(ModelMap model, HttpServletRequest request,HttpServletResponse response){
        String purchaseOrderHeaderId = StringUtils.trimToEmpty(request.getParameter("purchaseOrderHeaderId"));
        String expressNo = StringUtils.trimToEmpty(request.getParameter("expressNo"));
        if(BaseUtils.checkNullBlank(new String[]{purchaseOrderHeaderId})){
            PosPurchaseOrderHeader positionHeader = posPurchaseOrderHeaderService.getPosPurchaseOrderHeader(purchaseOrderHeaderId);
            if(positionHeader == null  || (positionHeader.getPosPurchaseOrderStatus() != null && !PosPurchaseOrderStatus.NEW.equals(positionHeader.getPosPurchaseOrderStatus()))){
                model.addAttribute("error","数据不存在或者单据状态不是新增");
                model.addAttribute("success",false);
            }else{
                PosPurchaseOrderDetail con = new PosPurchaseOrderDetail();
                con.setHeaderId(purchaseOrderHeaderId);
                List<PosPurchaseOrderDetail> detailList = posPurchaseOrderDetailService.getPosPurchaseOrderDetailList(con, null, null);
                Object o = request.getSession().getAttribute(BaseConstant.POSPURCHASEORDERITEM_SESSION_UPDATE);
                if(o == null){
                    model.addAttribute("error","session数据为空");
                    model.addAttribute("success",false);
                    return "message/messageJson";
                }else{
                    List<PosPurchaseOrderDetail> sessionItems = (List<PosPurchaseOrderDetail>)o;
                    if(sessionItems.isEmpty()){
                        model.addAttribute("error","session数据为空");
                        model.addAttribute("success",false);
                        return "message/messageJson";
                    }else{
                        List<PosPurchaseOrderDetail> waitDelItems = new ArrayList<PosPurchaseOrderDetail>();
                        List<PosPurchaseOrderDetail> waitAddItems = new ArrayList<PosPurchaseOrderDetail>();
                        //先找出需要删除的
                        for(PosPurchaseOrderDetail poi : detailList){
                            boolean needDel = true;
                            for(PosPurchaseOrderDetail tt : sessionItems){
                                if(tt.getDetailId() != null && tt.getDetailId().equals(poi.getDetailId())){
                                    needDel = false;
                                }
                            }
                            if(needDel){
                                waitDelItems.add(poi);
                            }
                        }
                        //最后找出需要添加的
                        for(PosPurchaseOrderDetail tt : sessionItems){
                            if(tt.getDetailId() == null){
                                tt.setPosPurchaseOrderHeader(positionHeader);
                                tt.setHeaderId(purchaseOrderHeaderId);
                                waitAddItems.add(tt);
                            }
                        }
                        //需要更新删除增加的订单项整理完毕
                        PosPurchaseOrderHeader waitUpdateHeader = null;
                        if(expressNo!=null && !positionHeader.getExpressNo().equals(expressNo)){
                            waitUpdateHeader = new PosPurchaseOrderHeader();
                            waitUpdateHeader.setHeaderId(purchaseOrderHeaderId);
                            waitUpdateHeader.setExpressNo(expressNo);
                        }
                        boolean flag = posPurchaseOrderHeaderService.updatePosPurchaseOrder(waitUpdateHeader, waitAddItems,waitDelItems);
                        model.addAttribute("success",flag);
                        return "message/messageJson";
                    }
                }
            }
        }else{
            model.addAttribute("error","参数错误");
            model.addAttribute("success",false);
        }
        return "message/messageJson";

    }

    /**
     * 删除采购单
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(controllerPath+"delPosPurchaseOrder.html")
    public String delPosPurchaseOrder(HttpServletRequest request,HttpServletResponse response, ModelMap model) {
        boolean flag = false;
        String headerId = StringUtils.trimToEmpty(request.getParameter("headerId"));
        if(BaseUtils.checkNullBlank(headerId)){
            flag = posPurchaseOrderHeaderService.cancelPosPurchase(headerId);
        }else{
            model.addAttribute("error","参数不能为空");
        }
        model.addAttribute("success",flag);
        return "message/messageJson";
    }

    /**
     * 审核采购单
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(controllerPath+"auditPosPurchaseOrder.html")
    public String auditPosPurchaseOrder(HttpServletRequest request,HttpServletResponse response, ModelMap model) {
        boolean flag = false;
        String headerId = StringUtils.trimToEmpty(request.getParameter("headerId"));
        String channelName = StringUtils.trimToEmpty(request.getParameter("channelName"));
        if(BaseUtils.checkNullBlank(new String[]{headerId,channelName})){
            flag = posPurchaseOrderHeaderService.auditPosPurchaseOrder(headerId,channelName);
        }else{
            model.addAttribute("error","参数不能为空");
        }
        model.addAttribute("success",flag);
        return "message/messageJson";
    }

}
